package com.jhx.video.discuss

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import cn.jzvd.JZVideoPlayer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Event
import com.jhx.common.model.Video
import com.jhx.common.utils.ImageLoader
import com.jhx.common.utils.UserManager
import com.jhx.common.utils.centerToast
import com.jhx.video.R
import com.jhx.video.model.Discuss
import com.jhx.video.model.VideoDetail
import com.jhx.video.utils.AppBarStatusChangeListener
import com.jhx.video.widget.ReplyDialog
import com.jhx.video.widget.VideoManagerDialog
import kotlinx.android.synthetic.main.fragment_discuss.*
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.*

/**
 * 视频正文页面
 *
 * @author Jack 2018-03-27 17:19
 */
class DiscussFragment : QuickBaseFragment(), Contract.DiscussView {
    private var mPageSize = 10
    private var mPageIndex = 1
    private var mVideo: Video? = null
    private var mVideoId: String? = ""
    private var mEmptyView: LinearLayout? = null
    private var mReplyDialog: ReplyDialog? = null
    private var mPresenter: DiscussPresenterImpl? = null
    private var mVidemManagerDialog: VideoManagerDialog? = null
    private var mAdapter: BaseQuickAdapter<Discuss, BaseViewHolder>? = null

    companion object {
        val KEY_VIDEO_ID = "video_id"
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_discuss, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mEmptyView = view?.findViewById(R.id.empty_layout)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mVideoId = arguments?.getString(KEY_VIDEO_ID)
        mPresenter = DiscussPresenterImpl()
        mPresenter?.setView(this)
        mPresenter?.getComment("$mVideoId", mPageIndex, mPageSize,
        onStart = {
            showLoading()
        },
        onComplete = {
            hideLoading()
        })
        initListener()
        initRecyclerView()
    }

    private fun initListener() {
        app_bar.addOnOffsetChangedListener(object: AppBarStatusChangeListener() {
            override fun onStateChanged(appBarLayout: AppBarLayout, state: Int) {
                when(state) {
                    AppBarStatusChangeListener.COLLAPSED -> {
                        val user = UserManager.get().user
                        if(user != null && !TextUtils.isEmpty(user.businessName)) {
                            toolbar_title.text = user.businessName
                        }
                    }
                    AppBarStatusChangeListener.EXPANDED -> toolbar_title.text = "视频正文"
                    AppBarStatusChangeListener.IDLE -> toolbar_title.text = "视频正文"
                }
            }
        })
        img_back.setOnClickListener {
            pop()
        }
        img_more.setOnClickListener {
            if(mVidemManagerDialog == null) {
                mVidemManagerDialog = VideoManagerDialog(activity!!)
            }
            if(mVideo?.is_top == Video.STATUS_ISTOP) {
                mVidemManagerDialog?.setTopText("取消置顶")
            } else {
                mVidemManagerDialog?.setTopText("置顶")
            }
            mVidemManagerDialog?.onItemClick = { _, index ->
                when(index) {
                    0 -> {
                        if(mVideo?.is_top == Video.STATUS_ISTOP) {
                            mPresenter?.stickVideo("$mVideoId", Video.STATUS_NOTTOP)
                        } else {
                            mPresenter?.stickVideo("$mVideoId", Video.STATUS_ISTOP)
                        }
                    }
                    1 -> {
                        mPresenter?.deleteVideo("$mVideoId")
                    }
                }
            }
            if(mVidemManagerDialog?.isShowing == false && activity?.isFinishing == false) {
                mVidemManagerDialog?.show()
            }
        }
    }

    private fun initRecyclerView() {
        mAdapter = object: BaseQuickAdapter<Discuss, BaseViewHolder>(R.layout.item_discuss) {
            @SuppressLint("SimpleDateFormat")
            override fun convert(holder: BaseViewHolder?, comment: Discuss?) {
                val replyTxt = holder?.getView<TextView>(R.id.txt_reply)
                val replyCl = holder?.getView<LinearLayout>(R.id.cl_reply)
                val lineView = holder?.getView<View>(R.id.view_line)
                if(comment?.children?.isNotEmpty() == true) {
                    replyCl?.visibility = View.VISIBLE
                    replyTxt?.visibility = View.GONE
                    lineView?.visibility = View.VISIBLE
                    ImageLoader.get().loadCircleImageByUrl(activity,
                            UserManager.get().user.headImage,
                            holder?.getView(R.id.img_head))
                    holder?.setText(R.id.txt_name, "${comment.children[0].userName}")
                    holder?.setText(R.id.txt_comment, "${comment.children[0].context}")
                    holder?.setText(R.id.txt_user_name, "${comment.userName} 回复：")
                    holder?.setText(R.id.txt_user_comment, "${comment.context}")
                } else {
                    lineView?.visibility = View.GONE
                    replyCl?.visibility = View.GONE
                    replyTxt?.visibility = View.VISIBLE
                    holder?.setText(R.id.txt_name, "${comment?.userName}")
                    holder?.setText(R.id.txt_comment, "${comment?.context}")
                    ImageLoader.get().loadCircleImageByUrl(activity, comment?.userHeadImg, holder?.getView(R.id.img_head))
                }
                if(comment?.createTime != null) {
                    val date = Date(comment.createTime!!.toLong())
                    val time = SimpleDateFormat("yyyy-MM-dd HH:mm").format(date)
                    holder?.setText(R.id.txt_date, time)
                }
                holder?.getView<TextView>(R.id.txt_reply)?.setOnClickListener {
                    if(mReplyDialog == null && activity?.isFinishing == false) {
                        mReplyDialog = ReplyDialog(activity!!)
                    }
                    mReplyDialog?.dismiss()
                    mReplyDialog?.onSendClick = { msg ->
                        mPresenter?.replyComment("${comment?.id}", "$msg")
                    }
                    if(activity?.isFinishing == false) {
                        mReplyDialog?.show()
                    }
                }
            }

        }
        mAdapter?.setOnLoadMoreListener({
            mPresenter?.getComment("$mVideoId", mPageIndex, mPageSize)
        }, recycler_view)
        recycler_view.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
        recycler_view.adapter = mAdapter
        recycler_view.layoutManager = LinearLayoutManager(activity)
        refresh_layout.setOnRefreshListener {
            mPageIndex = 1
            refresh_layout.isRefreshing = true
            mPresenter?.getComment("$mVideoId", mPageIndex, mPageSize)
        }
    }


    @SuppressLint("SimpleDateFormat")
    private fun initData() {
        videoview.setUp("${mVideo?.video_url}", JZVideoPlayer.SCREEN_WINDOW_LIST)
        ImageLoader.get().loadImageByUrl(activity, mVideo?.cover_url, videoview.thumbImageView)
        if(mVideo?.create_time != null) {
            val date = Date(mVideo!!.create_time!!)
            val time = SimpleDateFormat("MM-dd").format(date)
            txt_date.text = time
        }
        txt_share_num.text = "转发 ${mVideo?.share_video_num}"
        txt_comment_num.text = "评论 ${mVideo?.comment_num}"
        txt_collect_num.text = "赞 ${mVideo?.praise_num}"
        txt_desc.text = mVideo?.v_title
        txt_num.text =  mVideo?.play_num
        val user = UserManager.get().user
        if(user != null) {
            ImageLoader.get().loadCircleImageByUrl(activity, user.headImage, img_head)
            txt_name.text = user.businessName
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    override fun getCommentSuccess(data: VideoDetail?) {
        mVideo = data?.videoInfo
        initData()
        if(data?.comments?.isNotEmpty() == true) {
            mEmptyView?.visibility = View.GONE
            recycler_view.visibility = View.VISIBLE
            if(mPageIndex == 1) {
                refresh_layout.isRefreshing = false
                mAdapter?.data?.clear()
            } else {
                mAdapter?.loadMoreComplete()
            }
            mAdapter?.data?.addAll(data.comments!!)
            mAdapter?.notifyDataSetChanged()
            mPageIndex ++
        } else {
            if(mPageIndex == 1) {
                mEmptyView?.visibility = View.VISIBLE
            } else {
                mAdapter?.loadMoreEnd()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mReplyDialog?.dismiss()
        mReplyDialog = null
    }

    override fun requestError(url: String, msg: String) {
        refresh_layout.isRefreshing = false
        mAdapter?.loadMoreComplete()
    }

    @SuppressLint("MissingSuperCall")
    override fun onPause() {
        super.onPause()
        JZVideoPlayer.releaseAllVideos()
    }

    override fun getContext(): Activity {
        return activity!!
    }

    override fun deleteVideoSuccess() {
        activity?.centerToast("删除成功~")
        val event = Event()
        event.code = Video.CODE_DELETE_VIDEO
        EventBus.getDefault().post(event)
        pop()
    }

    override fun stickVideoSuccess() {
        if(mVideo?.is_top == Video.STATUS_NOTTOP) {
            activity?.centerToast("置顶成功")
            mVideo?.is_top = Video.STATUS_ISTOP
        } else {
            activity?.centerToast("取消置顶成功")
            mVideo?.is_top = Video.STATUS_NOTTOP
        }
        val event = Event()
        event.code = Video.CODE_TOP_VIDEO
        EventBus.getDefault().post(event)
    }

    override fun replyCommentSuccess() {
        mPageIndex = 1
        mPresenter?.getComment("$mVideoId", mPageIndex, mPageSize)
    }
}